package com.mini.mybatis.mybatisministep17.sqlsession.defaults;

import com.mini.mybatis.mybatisministep17.executor.Executor;
import com.mini.mybatis.mybatisministep17.mapping.Environment;
import com.mini.mybatis.mybatisministep17.sqlsession.SqlSession;
import com.mini.mybatis.mybatisministep17.sqlsession.SqlSessionFactory;
import com.mini.mybatis.mybatisministep17.sqlsession.TransactionIsolationLevel;
import com.mini.mybatis.mybatisministep17.sqlsession.configuration.Configuration;
import com.mini.mybatis.mybatisministep17.transaction.Transaction;
import com.mini.mybatis.mybatisministep17.transaction.TransactionFactory;

import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSession() {
        Transaction tx = null;
        try {
            Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();
            tx = transactionFactory.newTransaction(environment.getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);
            Executor executor = configuration.newExecutor(tx);
            return new DefaultSqlSession(configuration, executor);
        }catch (Exception e){
            try {
                assert tx != null;
                tx.close();
            }catch (SQLException sqlException){}
            throw new RuntimeException("Error opening session.  Cause: " + e);
        }
    }
}
